package com.snap.vseries.adapter;

import android.content.Context;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.base.BaseRecycleAdapter;
import com.snap.vseries.base.BaseViewHolder;
import com.snap.vseries.base.OnItemClickListener;
import com.snap.vseries.bean.ProgramRecycle;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.utils.NumberLimitUtils;
import com.snap.vseries.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

public class NewExpCycleStageAdapter extends BaseRecycleAdapter<ProgramRecycle> {
    private int size;
    private OnItemClickListener onItemClickListener;
    private OnItemClickListener onItemDeleteClickListener;
    private Context context;
    private List<ProgramRecycle> dataList;


    public NewExpCycleStageAdapter(Context context, List<ProgramRecycle> dataList, int size) {
        super(context, dataList);
        this.context = context;
        this.size = size;
        this.dataList = dataList;
    }

    @Override
    public void bindData(BaseViewHolder holder, ProgramRecycle data, int position) {
        initDelete(holder, data);
        initRecycleCount(holder, data);
        initSpinner(data, holder);
    }

    private void initSpinner(ProgramRecycle data, BaseViewHolder holder) {
        final boolean[] isStartFirst = {true};
        final boolean[] isEndFirst = {true};
        HashMap<Integer, Integer> usedMap;
        Spinner startSp = holder.getView(R.id.left_sp);
        Spinner endSp = holder.getView(R.id.right_sp);
        usedMap = new HashMap<>();
        for (int i = 0; i < dataList.size(); i++) {
            ProgramRecycle programRecycle = dataList.get(i);
            if (programRecycle == data) {
                continue;
            }
            if (programRecycle.getStartIndex() == -1) {
                continue;
            }
            if (programRecycle.getEndIndex() == -1) {
                if (!usedMap.containsKey(programRecycle.getStartIndex())) {
                    usedMap.put(programRecycle.getStartIndex(), programRecycle.getStartIndex());
                }
                continue;
            }
            for (int j = programRecycle.getStartIndex(); j <= programRecycle.getEndIndex(); j++) {
                if (!usedMap.containsKey(j)) {
                    usedMap.put(j, j);
                }
            }
        }
        List<String> startList = new ArrayList<>();
        for (int i = 1; i <= size; i++) {
            if (!usedMap.containsKey(i)) {
                startList.add(String.format(Locale.CHINA, "Stage %02d", i));
            }
        }
        if (startList.size() == 0) {
            startSp.setEnabled(false);
            startList.add("-");
        } else {
            startSp.setEnabled(true);
        }
        List<String> endList = new ArrayList<>();
        if (data.getStartIndex() != -1) {
            endSp.setEnabled(true);
            for (int i = data.getStartIndex(); i <= size; i++) {
                if (!usedMap.containsKey(i)) {
                    endList.add(String.format(Locale.CHINA, "Stage %02d", i));
                } else {
                    break;
                }
            }
        } else {
            endList.add("-");
            endSp.setEnabled(false);
        }
        //初始化数据
        ArrayAdapter<String> startAdapter = new ArrayAdapter<>(mContext, R.layout.spinner_layout, startList);
        ArrayAdapter<String> endAdapter = new ArrayAdapter<>(mContext, R.layout.spinner_layout, endList);
        startSp.setAdapter(startAdapter);
        endSp.setAdapter(endAdapter);

        if (data.getStartIndex() != -1) {
            for (int i = 0; i < startList.size(); i++) {
                Pattern pattern = Pattern.compile(" ");
                String[] strs = pattern.split(startList.get(i));
                if (data.getStartIndex() == Integer.parseInt(strs[1])) {
                    startSp.setSelection(i);
                    break;
                }
            }
        }
        if (data.getEndIndex() != -1) {
            for (int i = 0; i < endList.size(); i++) {
                Pattern pattern = Pattern.compile(" ");
                String[] strs = pattern.split(endList.get(i));
                if (data.getEndIndex() == Integer.parseInt(strs[1])) {
                    endSp.setSelection(i);
                    break;
                }
            }
        }
        startSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                TextView tv = (TextView) view;
                if (tv == null) {
                    return;
                }

                if (isStartFirst[0] && data.getStartIndex() == -1) {
                    tv.setTextColor(0xFFC1C3CF);
                    tv.setText("-");
                    isStartFirst[0] = false;
                    return;
                } else {
                    tv.setTextColor(0xFF568BFF);
                }
                if (tv.getText().toString().equals("-")) {
                    tv.setText(startList.get(position));
                }
                Pattern pattern = Pattern.compile(" ");
                String[] strs = pattern.split(tv.getText().toString());
                data.setStartIndex(Integer.parseInt(strs[1]));
                ((TextView) holder.getView(R.id.tv_recycle_count)).setTextColor(0xFFEBECF0);
                if (data.getCycleCount() == 0) {
                    data.setCycleCount(40);
                }
                ((TextView) (holder.getView(R.id.tv_recycle_count))).setText(String.valueOf(data.getCycleCount()));
                holder.getView(R.id.tv_recycle_count).setEnabled(false);
                if (!isStartFirst[0]) {
                    data.setEndIndex(-1);
                    notifyDataSetChanged();
                } else {
                    isStartFirst[0] = false;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        endSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                TextView tv = (TextView) view;
                if (tv == null) {
                    return;
                }
                if (isEndFirst[0] && data.getEndIndex() == -1) {
                    tv.setTextColor(0xFFC1C3CF);
                    tv.setText("-");
                    isEndFirst[0] = false;
                    return;
                } else {
                    tv.setTextColor(0xFF568BFF);
                }
                if (tv.getText().toString().equals("-")) {
                    tv.setText(endList.get(position));
                }
                Pattern pattern = Pattern.compile(" ");
                String[] strs = pattern.split(tv.getText().toString());
                if (strs.length > 1) {
                    data.setEndIndex(Integer.parseInt(strs[1]));
                }
                onItemClickListener.onItemClick(NewExpCycleStageAdapter.this, view, position);
                ((TextView) holder.getView(R.id.tv_recycle_count)).setTextColor(0xFF568BFF);
                holder.getView(R.id.tv_recycle_count).setEnabled(true);
                if (!isEndFirst[0]) {
                    notifyDataSetChanged();
                } else {
                    isEndFirst[0] = false;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    /**
     * FFEBECF0
     *
     * @param holder
     * @param data
     */
    private void initRecycleCount(BaseViewHolder holder, ProgramRecycle data) {
        holder.setText(R.id.tv_recycle_count, String.valueOf(data.getCycleCount())).setOnItemClickLitener(new BaseViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                if (data.getStartIndex() == -1 | data.getEndIndex() == -1) {
                    return;
                }
                new DialogView(context)
                        .setTitle("修改运行次数")
                        .setHint("请输入运行次数")
                        .setContentNumberType()
                        .setContentNumberType(InputType.TYPE_CLASS_NUMBER)
                        .setOnClickListener(content -> {
                            if (content.isEmpty()) {
                                ToastUtils.get().showText("运行次数不允许为空");
                                return;
                            }
                            if (!NumberLimitUtils.numberLimit(content, "100", "2")) {
                                return;
                            }
                            long count = Long.parseLong(content);
                            data.setCycleCount((int) count);
                            holder.setText(R.id.tv_recycle_count, String.valueOf(count));
                        })
                        .show();
            }
        });
    }

    private void initDelete(BaseViewHolder holder, ProgramRecycle data) {
        holder.getView(R.id.delete_stage_btn).setOnClickListener(v -> {
            dataList.remove(data);
            onItemDeleteClickListener.onItemClick(NewExpCycleStageAdapter.this, null, 0);
        });
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemDeleteClickListener(OnItemClickListener onItemDeleteClickListener) {
        this.onItemDeleteClickListener = onItemDeleteClickListener;
    }

    @Override
    public int getLayoutId(int viewType) {
        return R.layout.item_experiment_recyle_stage;
    }

    public void updateData(List<ProgramRecycle> dataList, int size) {
        this.size = size;
        this.dataList = dataList;
        super.updateData(dataList);
    }

    public void notifyItemChangedLast(List<ProgramRecycle> dataList) {
        this.dataList = dataList;
        notifyItemChanged(dataList.size() - 1);
    }
}
